export class EventBase {
    //#region 事件定义
    private _emitter: any;
    //#endregion
    
    /**
     * 订阅事件
     * @param eventName 
     * @param listener 
     */
    public addListener(eventName: string , listener: (...args: any[]) => void) {
        if (typeof(listener) !== 'function') return;
        let events;
        this._emitter = this._emitter || {};
        if (this._emitter.hasOwnProperty(eventName)) {
            events  = this._emitter[eventName];
        }
        if (!events) {
            this._emitter[eventName] = [];
        }
        this._emitter[eventName].push(listener);
    }
    /**
     * 移除事件
     * @param eventName 
     * @param listener 
     */
    public removeListener(eventName: string , listener: (...args: any[]) => void) {
        if (typeof(listener) !== 'function') return;
        let events;
        this._emitter = this._emitter || {};
        if (this._emitter.hasOwnProperty(eventName)) {
            events  = this._emitter[eventName];
        }
        if (events) {
            for (let index = events.length - 1 ; index >= 0; index--) {
                if (events[index] === listener) {
                    events = events.splice(index, 1);
                    this._emitter[eventName] = events;
                }
            }
        }
    }
    /**
     * 发布事件
     * @param eventName 
     * @param args 
     */
    protected publishEvent (eventName: string, ...args: any[]) {
        let events;
        this._emitter = this._emitter || {};
        if (this._emitter.hasOwnProperty(eventName)) {
            events  = this._emitter[eventName];
        }
        if (events) {
            events.forEach((value: any) => {
                if (typeof(value) === 'function') {
                    value.apply(this, args);
                }
            });
        }
    }
}